package com.visionet.waveletData.web.interceptor;

import com.google.common.collect.Lists;
import com.visionet.waveletData.web.common.constant.BusinessStatus;
import com.visionet.waveletData.web.common.constant.SysConstants;
import com.visionet.waveletData.web.common.utilities.props.PropsKeys;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;
import com.visionet.waveletData.web.common.utilities.string.GetterUtil;
import com.visionet.waveletData.web.web.BaseController;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

public class UserLogInterceptor extends HandlerInterceptorAdapter{
	
	private static Logger _log = LoggerFactory.getLogger(UserLogInterceptor.class);
	public static boolean LogFlag = GetterUtil.getBoolean(PropsUtil.getProperty(PropsKeys.AUDIT_LOG_ENABLED), false);
	private NamedThreadLocal<Long>  startTimeThreadLocal =  new NamedThreadLocal<Long>("StopWatch-StartTime");
    private static final List<String> urlList = Lists.newArrayList("/console/2.0/role/allPermissions");

    /**
	 * 预处理,Controller之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
//        UserCountScanner.VisitsNum++;

//        Long currUserId  = null;
//        if(!uri.contains("/weblogin")){
//            try{
//                currUserId = BaseController.getCurrentUserId();
//            }catch (Exception e){
//                _log.error(e.toString());
//            }
//            if(currUserId == null) {
//                response.setHeader("sessionInvalid", "true");
//            }
//        }
        if(uri.contains("/web/") &&
                !BaseController.hasRole(Lists.newArrayList(SysConstants.ADMIN, SysConstants.SUBADMIN, SysConstants.MEETINGADM))
                ){
            boolean ignore = false;
            for(String ignoreUri: urlList){
                if(uri.contains(ignoreUri)){
                    ignore = true;
                    break;
                }
            }
            if(!ignore){
                throw new UnauthorizedException(BusinessStatus.USERDENY);
            }

        }
		if(LogFlag){
			//1、开始时间  
			long beginTime = System.currentTimeMillis();
			//线程绑定变量（该数据只有当前请求的线程可见）
			startTimeThreadLocal.set(beginTime);
		}
		return super.preHandle(request, response, handler);
	}

	/**
	 * 生成视图之前,调用了Service并返回ModelAndView，但未进行页面渲染
	 */
	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception{

		super.postHandle(request, response, handler, modelAndView);
	}
	
	/**
	 * 最后执行，可用于释放资源
	 * 可以根据ex是否为null判断是否发生了异常，进行日志记录
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{
	
		String uri = request.getRequestURI();

        Long currUserId  = null;
		if(!uri.contains("/weblogin")){
            try{
                currUserId = BaseController.getCurrentUserId();
            }catch (Exception e){
                _log.error(e.toString());
            }
//            if(currUserId == null) {
//                response.setHeader("sessionInvalid", "true");
//            }
		}


		if(LogFlag){
			if(currUserId==null) return;

			uri = uriProcess(uri);

//			Button bt = ButtonService.getButtonStartsWithUri(uri);


//			if(bt!=null && checkUri(uri,bt,request.getMethod())){
//				_log.debug("--userId:"+currUserId+" ----uri:"+uri+" :"+request.getMethod() );
//
//				UserActionLog actionlog = new UserActionLog();
//				actionlog.setUserId(currUserId);
//				actionlog.setUserName(BaseController.getCurrentUserName());
//				actionlog.setUrl(uri);
//				actionlog.setActionType(bt.getActionType());
//				actionlog.setUrlDesc(bt.getUrlDesc());
//				if(bt.getId()!=null) actionlog.setFkId(bt.getId());
//				
//				//2、结束时间 
//				long endTime = System.currentTimeMillis(); 
//				//得到线程绑定的局部变量（开始时间）  
//				long beginTime = startTimeThreadLocal.get();
//				//3、消耗的时间
//				long consumeTime = endTime - beginTime;
//		        
//				actionlog.setConsumeTime(consumeTime);
//				if(ex!=null){
//					actionlog.setExcptionMsg("ex:"+ex.toString());
//				}
//
//				UserActionLogService.saveActionLog(actionlog);
//			}
//			_log.debug("view name : " +modelAndView.getViewName());

		}
		
		super.afterCompletion(request, response, handler, ex);
	}
	
	
//	private static boolean checkUri(String uri,Button bt,String methodType){
//	
//		if("Y".equals(bt.getNeedLog()) && methodType.equals(bt.getHttpType())){
//			return true;
//		}
//		
//		return false;
//	}
	
	private static String uriProcess(String uri){
		
		return uri;
	}
}
